package com.corner.presenter.imp;

import android.database.Cursor;

import com.corner.app.App;
import com.corner.model.db.DBConstans;
import com.corner.model.db.Session;
import com.corner.model.db.SessionDao;
import com.corner.presenter.INotifyPresenter;
import com.corner.presenter.base.BasePresenter;
import com.corner.ui.view.INotifyView;

import java.util.Date;
import java.util.List;
import java.util.Observer;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2015/7/15，13.50.
 * 描述：
 */
public class NotifyPresenter extends BasePresenter<INotifyView> implements INotifyPresenter, Observer {

    /**
     * 最后一条记录的时间
     */
    private Date lastItemTime;
    private boolean hasMore;
    private List<Session> sessionList;

    /**
     * 设置最后一条记录的时间
     */
    private void setFirstTime() {
        if (sessionList.size() > 0) {
            lastItemTime = sessionList.get(sessionList.size() - 1).getTimestamp();
        }
    }

    public NotifyPresenter() {
        App.application.daoSession.getSessionDao().addObserver(NotifyPresenter.this);
    }

    @Override
    public void refresh() {

        Observable.create(new Observable.OnSubscribe<List<Session>>() {
            @Override
            public void call(Subscriber<? super List<Session>> subscriber) {
                if (lastItemTime == null) {

                    Cursor cursor = App.application.daoSession.getSessionDao().getDatabase().query(
                            App.application.daoSession.getSessionDao().getTablename(), null,
                            SessionDao.Properties.Type.columnName + " = ? ", new String[]{DBConstans.LIKE},
                            SessionDao.Properties.SessionName.columnName, null, SessionDao.Properties.Timestamp.columnName + " desc",
                            "10");
                    sessionList = App.application.daoSession.getSessionDao().cursorToList(cursor);
                    cursor.close();
                } else {
                    Cursor cursor = App.application.daoSession.getSessionDao().getDatabase().query(
                            App.application.daoSession.getSessionDao().getTablename(), null,
                            SessionDao.Properties.Type.columnName + " = ? and " + SessionDao.Properties.Timestamp.columnName + " >= ?", new String[]{DBConstans.LIKE, lastItemTime.getTime() + ""},
                            SessionDao.Properties.SessionName.columnName, null, SessionDao.Properties.Timestamp.columnName + " desc");
                    sessionList = App.application.daoSession.getSessionDao().cursorToList(cursor);
                    cursor.close();
                }
                if (sessionList == null || sessionList != null && sessionList.size() == 0) {
                    hasMore = false;
                } else {
                    if (sessionList.size() < 10) {
                        hasMore = false;
                    }
                    setFirstTime();
                    subscriber.onNext(sessionList);
                }
                setFirstTime();
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<List<Session>>() {
            @Override
            public void onCompleted() {
                if (view != null)
                    view.refreshComplete();
            }

            @Override
            public void onError(Throwable e) {
                if (view != null)
                    view.refreshComplete();
            }

            @Override
            public void onNext(List<Session> sessions) {
                if (view != null) {
                    view.showRefreshSession(sessions);
                    view.refreshComplete();
                    view.setLoadMoreEnable(hasMore);
                }
            }
        });
    }

    @Override
    public void loadMore() {
        if (!hasMore || sessionList == null) {
            view.loadMoreComplete();
            return;
        }
        Observable.create(new Observable.OnSubscribe<List<Session>>() {
            @Override
            public void call(Subscriber<? super List<Session>> subscriber) {
                Cursor cursor = App.application.daoSession.getSessionDao().getDatabase().query(
                        App.application.daoSession.getSessionDao().getTablename(), null,
                        SessionDao.Properties.Type.columnName + " = ? and " + SessionDao.Properties.Timestamp.columnName + " < ?", new String[]{DBConstans.LIKE, lastItemTime.getTime() + ""},
                        SessionDao.Properties.SessionName.columnName, null, SessionDao.Properties.Timestamp.columnName + " desc",
                        "10");
                List<Session> presessions = App.application.daoSession.getSessionDao().cursorToList(cursor);
                cursor.close();

                if (presessions == null || presessions != null && presessions.size() == 0) {
                    hasMore = false;
                } else {
                    if (presessions.size() < 10) {
                        hasMore = false;
                    }
                    presessions.addAll(sessionList);
                    sessionList = presessions;
                    setFirstTime();
                    subscriber.onNext(sessionList);
                }
                subscriber.onCompleted();
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<List<Session>>() {
            @Override
            public void onCompleted() {
                if (view != null)
                    view.loadMoreComplete();
            }

            @Override
            public void onError(Throwable e) {
                if (view != null)
                    view.loadMoreComplete();
            }

            @Override
            public void onNext(List<Session> sessions) {
                if (view != null) {
                    view.showLoadMoreSession(sessions);
                    view.loadMoreComplete();
                    view.setLoadMoreEnable(hasMore);
                }
            }
        });
    }

    @Override
    public void update(java.util.Observable observable, Object data) {
        refresh();
    }

    @Override
    public void onDestroy() {
        App.application.daoSession.getSessionDao().deleteObserver(this);
        super.onDestroy();
    }
}
